/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package formularios;

import controlo.ControloVendas;
import java.util.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;


import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import modelo.ModeloTabela;
import modelo.Modelo_Vendas;
import utilizador_bd.ConectBD;

/**
 *
 * @author Daniel
 */
public class Vendas extends javax.swing.JFrame {
    ConectBD conect = new ConectBD();
    ConectBD conectprod = new ConectBD();
    Modelo_Vendas mod = new Modelo_Vendas();
    controlo.ControloVendas controlo = new ControloVendas();
    int flag = 1, codvendas ;
private String SQL;

float preco_produto,total=0;

    public Vendas() {
        
        
        initComponents();
        SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
      Date hoje = new Date();
       jFormattedTextField1.setText(df.format(hoje));
    
        
     
        
        
       
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton1add = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1pesquisa = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jTextField1nomecliente = new javax.swing.JTextField();
        jTextField1prod = new javax.swing.JTextField();
        jButton2busccliente = new javax.swing.JButton();
        jButton3prod = new javax.swing.JButton();
        jTextField1qnt = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextField1valorpitem = new javax.swing.JTextField();
        jComboBox1desconto = new javax.swing.JComboBox();
        jLabel8 = new javax.swing.JLabel();
        jTextField1valortotal = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2itens = new javax.swing.JTable();
        jLabel10 = new javax.swing.JLabel();
        jButton1finvenda = new javax.swing.JButton();
        jButton2canpedido = new javax.swing.JButton();
        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jTextField1iva = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setToolTipText("Vendas");

        jButton1add.setText("ADD");
        jButton1add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1addActionPerformed(evt);
            }
        });

        jTable1pesquisa.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1pesquisa.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1pesquisaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1pesquisa);

        jLabel1.setText("Produtos");

        jLabel3.setText("Nome do cliente");

        jLabel4.setText("Iva");

        jLabel5.setText("Desconto");

        jLabel6.setText("Data");

        jLabel7.setText("Quantidade");

        jButton2busccliente.setText("Busca");
        jButton2busccliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2buscclienteActionPerformed(evt);
            }
        });

        jButton3prod.setText("Busca");
        jButton3prod.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3prodActionPerformed(evt);
            }
        });

        jTextField1qnt.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTextField1qntFocusGained(evt);
            }
        });

        jLabel2.setText("Valor Por Item");

        jComboBox1desconto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel8.setText("Tabela de pesquisa");

        jLabel9.setText("ValorTotal");

        jTable2itens.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable2itens);

        jLabel10.setText("Itens da Venda");

        jButton1finvenda.setText("Finalizar Venda");
        jButton1finvenda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1finvendaActionPerformed(evt);
            }
        });

        jButton2canpedido.setText("Cancelar Pedido");

        jFormattedTextField1.setText("jFormattedTextField1");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(0, 610, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(28, 28, 28)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel7)
                                    .addComponent(jTextField1qnt, javax.swing.GroupLayout.DEFAULT_SIZE, 64, Short.MAX_VALUE)
                                    .addComponent(jLabel4)
                                    .addComponent(jTextField1iva)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(193, 193, 193)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel2)
                                    .addComponent(jTextField1valorpitem, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1add, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(25, 25, 25))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(76, 76, 76)
                        .addComponent(jButton2canpedido)
                        .addGap(36, 36, 36)
                        .addComponent(jButton1finvenda)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel9)
                        .addGap(51, 51, 51)
                        .addComponent(jTextField1valortotal, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(69, 69, 69))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(197, 197, 197)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel5)
                                    .addComponent(jComboBox1desconto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTextField1nomecliente, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton2busccliente)
                                .addGap(62, 62, 62)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jTextField1prod, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jButton3prod))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel6)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(78, 78, 78)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 424, Short.MAX_VALUE)
                                    .addComponent(jLabel8)
                                    .addComponent(jLabel10)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1nomecliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2busccliente)
                    .addComponent(jTextField1prod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton3prod))
                .addGap(19, 19, 19)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(9, 9, 9)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBox1desconto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField1iva, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel7))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextField1qnt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jTextField1valorpitem, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGap(9, 9, 9)
                            .addComponent(jButton1add, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jFormattedTextField1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(26, 26, 26)
                .addComponent(jLabel8)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, Short.MAX_VALUE)
                .addComponent(jLabel10)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(jTextField1valortotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2canpedido)
                    .addComponent(jButton1finvenda))
                .addContainerGap(64, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(22, 22, 22))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
public void preencherTabelaproduto(String sql){
        ArrayList dados = new ArrayList();
        
        String [] Colunas = new String[]{"Cod_prod", "Nome produto","Quantidade"};
        conect.conexao();
        conect.executaSQL(sql);
          try {
              conect.re.first();
              
                do{
         dados.add(new Object[]{conect.re.getString("cod_prod"),conect.re.getString("descricao"),conect.re.getString("quantidade")});
     } while(conect.re.next());
     
          } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Erro no array!\n Erro:" +ex.getMessage());
          }
          
        ModeloTabela modelo  = new ModeloTabela(dados, Colunas);
     
     jTable1pesquisa.setModel(modelo);
     jTable1pesquisa.getColumnModel().getColumn(0).setPreferredWidth(110);
     jTable1pesquisa.getColumnModel().getColumn(0).setResizable(false);
     jTable1pesquisa.getColumnModel().getColumn(1).setResizable(false);
     jTable1pesquisa.getColumnModel().getColumn(1).setPreferredWidth(110);
     jTable1pesquisa.getColumnModel().getColumn(2).setResizable(false);
     jTable1pesquisa.getColumnModel().getColumn(2).setPreferredWidth(110);

     jTable1pesquisa.getTableHeader().setReorderingAllowed(false);
     jTable1pesquisa.setAutoResizeMode(jTable1pesquisa.AUTO_RESIZE_OFF);
     jTable1pesquisa.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);}



    private void jButton2buscclienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2buscclienteActionPerformed
       
        flag=1;
        preencherTabelacliente("select * from clientes where nome like '%"+jTextField1nomecliente.getText()+"%'");
    }//GEN-LAST:event_jButton2buscclienteActionPerformed

    
    
    public void preencherItensVenda(String sql){
        ArrayList dados = new ArrayList();
        
        String [] Colunas = new String[]{"Descrição", "Quantidade","ValorTotal"};
        conect.conexao();
        conect.executaSQL(sql);

          try {
              conect.re.first();
              
                do{
                    float valorProduto = conect.re.getFloat("valorvendap");
                    int quantidadeVendida = conect.re.getInt("quantidade_produto");
                    
         dados.add(new Object[]{conect.re.getString("descricao"),conect.re.getString("quantidade_produto"), valorProduto*quantidadeVendida});
     } while(conect.re.next());
   
          } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Erro no array!\n Erro:" +ex.getMessage());
          }
          
        ModeloTabela modelo  = new ModeloTabela(dados, Colunas);
     
     jTable2itens.setModel(modelo);
     jTable2itens.getColumnModel().getColumn(0).setPreferredWidth(100);
     jTable2itens.getColumnModel().getColumn(0).setResizable(false);
     jTable2itens.getColumnModel().getColumn(1).setResizable(false);
     jTable2itens.getColumnModel().getColumn(1).setPreferredWidth(100);
     jTable2itens.getColumnModel().getColumn(2).setResizable(false);
     jTable2itens.getColumnModel().getColumn(2).setPreferredWidth(100);
   
     jTable2itens.getTableHeader().setReorderingAllowed(false);
     jTable2itens.setAutoResizeMode(jTable2itens.AUTO_RESIZE_OFF);
     jTable2itens.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);}
   
    
    private void jButton3prodActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3prodActionPerformed
       
         conect.conexao();
        
        try {
            PreparedStatement pst = conect.con.prepareStatement("insert into vendas (valortotal)value(?)");
            pst.setFloat(1,0);
            pst.execute();
            conect.executaSQL("select * from vendas");
            conect.re.last();
            codvendas = conect.re.getInt("cod_vendas");
            
        } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Erro !\n Erro:" +ex.getMessage());
        }
        flag=2;
        preencherTabelaproduto("select * from produtos where descricao like '%"+jTextField1prod.getText()+"%'");
    }//GEN-LAST:event_jButton3prodActionPerformed

    
    
    private void jTable1pesquisaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1pesquisaMouseClicked
if(flag==1){
    String nome = "" + jTable1pesquisa.getValueAt(jTable1pesquisa.getSelectedRow(), 1);
    
    jTextField1nomecliente.setText(nome);
}
else{
       
    try {
         String nome = "" + jTable1pesquisa.getValueAt(jTable1pesquisa.getSelectedRow(), 1);
        conect.executaSQL("select * from produtos where descricao ='"+nome+"'");

        conect.re.first();
        preco_produto=conect.re.getFloat("valorvendap");
        jTextField1valorpitem.setText(String.valueOf(preco_produto));
        jTextField1qnt.setText("1");
        jTextField1prod.setText(nome);

    } catch (SQLException ex) {
JOptionPane.showMessageDialog(rootPane, "Erro ao pesquisar preço!"+ex.getMessage());
        
        }

        

}
    }//GEN-LAST:event_jTable1pesquisaMouseClicked

    private void jTextField1qntFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextField1qntFocusGained
        float valortotal;
         
        valortotal = Integer.parseInt(jTextField1qnt.getText())*Float.parseFloat(jTextField1valorpitem.getText());
        jTextField1valortotal.setText(String.valueOf(valortotal));    
    }//GEN-LAST:event_jTextField1qntFocusGained

    
    
    
    
    private void jButton1addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1addActionPerformed
        try {
            int id_venda, quantidade=0;
            conect.conexao();
            
            conect.executaSQL("select * from produtos where descricao='"+jTextField1prod.getText()+"'");

            conect.re.first();
            quantidade = conect.re.getInt("quantidade");
            if(quantidade >= Integer.parseInt(jTextField1qnt.getText())){
            

            mod.setProdutosvendas(jTextField1prod.getText());
            mod.setQuantidade(Integer.parseInt(jTextField1qnt.getText()));
            
            mod.setClientesvendas(jTextField1nomecliente.getText());
            mod.setCod_vendas(codvendas);
            controlo.Inserirvendas(mod);
            
             preencherItensVenda("select * from produtos inner join items_prod_vendas on produtos.cod_prod = items_prod_vendas.id_produto inner join vendas on vendas.cod_vendas = items_prod_vendas.id_venda where vendas.cod_vendas="+codvendas);
         conect.executaSQL("select * from clientes where nome='"+jTextField1nomecliente.getText()+"'");

            
            
            }else{
                
                           JOptionPane.showMessageDialog(rootPane, "A quantidade selecionada não está disponível");

            
            }
            
            
            total = total + Float.parseFloat(jTextField1valorpitem.getText())* Integer.parseInt(jTextField1qnt.getText());
            jTextField1valortotal.setText(String.valueOf(total));
            
           
        } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Erro a pesquisar quantidade:" +ex.getMessage());
        }
    }//GEN-LAST:event_jButton1addActionPerformed

    private void jButton1finvendaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1finvendaActionPerformed
mod.setClientesvendas(jTextField1nomecliente.getText());
mod.setCod_vendas(codvendas);
mod.setData(jFormattedTextField1.getText());
mod.setValortotal(Float.parseFloat(jTextField1valortotal.getText()));
controlo.fechaVenda(mod);
dispose();
    }//GEN-LAST:event_jButton1finvendaActionPerformed

    
    public void somaProduto(){
       total=0;
        conect.executaSQL("select * from items_prod_vendas inner join produtos on items_prod_vendas.id_produto = produtos.cod_prod where id_venda="+codvendas);

        
        try {
            conect.re.first();
            while(conect.re.next()) {
                total = total + conect.re.getFloat("valorvendap")* conect.re.getInt("quantidade_produto")*conect.re.getFloat("ivaprod");
            }
            
            jTextField1valortotal.setText(String.valueOf(total));
            
        } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Erro na soma:" +ex.getMessage());
        }
        
        
    }
    
    public void preencherTabelacliente(String sql){
        ArrayList dados = new ArrayList();
        
        String [] Colunas = new String[]{"NrCartão", "Nome"};
        conect.conexao();
        conect.executaSQL(sql);
          try {
              conect.re.first();
              
                do{
         dados.add(new Object[]{conect.re.getString("nrcartao"),conect.re.getString("nome")});
     } while(conect.re.next());
     
          } catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, "Erro no array!\n Erro:" +ex.getMessage());
          }
          
        ModeloTabela modelo  = new ModeloTabela(dados, Colunas);
     
     jTable1pesquisa.setModel(modelo);
     jTable1pesquisa.getColumnModel().getColumn(0).setPreferredWidth(110);
     jTable1pesquisa.getColumnModel().getColumn(0).setResizable(false);
     jTable1pesquisa.getColumnModel().getColumn(1).setResizable(false);
     jTable1pesquisa.getColumnModel().getColumn(1).setPreferredWidth(110);
    

     jTable1pesquisa.getTableHeader().setReorderingAllowed(false);
     jTable1pesquisa.setAutoResizeMode(jTable1pesquisa.AUTO_RESIZE_OFF);
     jTable1pesquisa.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);}
     
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Vendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Vendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Vendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Vendas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Vendas().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1add;
    private javax.swing.JButton jButton1finvenda;
    private javax.swing.JButton jButton2busccliente;
    private javax.swing.JButton jButton2canpedido;
    private javax.swing.JButton jButton3prod;
    private javax.swing.JComboBox jComboBox1desconto;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1pesquisa;
    private javax.swing.JTable jTable2itens;
    private javax.swing.JTextField jTextField1iva;
    private javax.swing.JTextField jTextField1nomecliente;
    private javax.swing.JTextField jTextField1prod;
    private javax.swing.JTextField jTextField1qnt;
    private javax.swing.JTextField jTextField1valorpitem;
    private javax.swing.JTextField jTextField1valortotal;
    // End of variables declaration//GEN-END:variables
}
